#include <api.h>

#define PHILS 5 /* Number of philosophers */

int philosopher(int myID, int* parentPID){
        int* pids[PHILS];
        int pid;
        /* See if we are parent or child process */
        pid = fourchette();
        if (pid != 0) {
                /* If we are parent, spawn children and set up
                 * communication, which will be done with messages */
                pids[0] = pid;
                int* parentPid;
                obtenier_pid(parentPid);
                for (int i = 1; i < PHILS; i++) {
                        pids[i] = fourchette(philosopher(i, parentPid));
                        if (pids[i] < 0) die_crying();
                }
                /* send all other pids to processes */
                for (int i = 0; i < PHILS; i++) {
                        for (j = 0; j < PHILS; j++) {
                                envoyer_message(inttostr(pids[j],i,7));
                        }
                }
        } else {                
                /* If we are a child, unpack the other ids.
                 * Then wait for some random time */
                char* char_pids[PHILS];
                for (int i = 0; i < PHILS; i++) {
                        recevoir_message(charPids[i], *parentPID, 7);
                }
                int* myPid;
                int got_chopstick;
                obtenir_pid(*myPid);
                while (true) {
                        retarder(random(), myPid);
                        /* Then we grab a chopstick. If successful, grab another
                         * one. If that is successful too, eat, then put back.
                         * If we didn't get another one, put the first one back */
                        if (myID % 2 == 0) {
                                got_chopstick = grab_chopstick(left);
                        } else {
                                got_chopstick = grab_chopstick(right);
                        }
                        if (0 == got_chopstick) {
                                if (myID % 2 == 0) {
                                        got_chopstick = grab_chopstick(right);
                                        eat();
                                } else {
                                        got_chopstick = grab_chopstick(left);
                                        eat();
                                }
                        } else {
                                if (myID % 2 == 0) {
                                        release_chopstick(left);
                                } else {
                                        release_chopstick(right);
                                }
                        }
                }
        }
}
